package com.banji.gupiao.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.banji.gupiao.model.GuPiaoFenHong;
import com.banji.gupiao.model.GuPiaoSYL;
import com.banji.gupiao.model.GuPiaoXianJinLiu;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 股票代码开头有何含义？
 * 1、沪市主板：股票代码以600、601或603开头。
 * 2、深市主板：股票代码以000、001、002、003开头。
 * 3、创业板：股票代码以300开头，创业板属于深证市场。
 * 4、科创板：股票代码以688开头，科创板属于上证市场。
 * 5、新三板：股票代码通常以400、430、830开头。
 */
@Service
public class GuPiaoDataManager {

    // 网站爬取首页：http://quote.eastmoney.com/center/gridlist.html#hs_a_board

    // 首页爬取地址
    private final String homePageUrl = "https://12.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=10000&po=1&np=1&fltt=2&invt=2&wbp2u=|0|0|0|web&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048&fields=f12,f14,f115";

    // 分红融资-分红方案：
    // https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_DIVIDEND_MAIN&columns=SECUCODE%2CSECURITY_CODE%2CSECURITY_NAME_ABBR%2CNOTICE_DATE%2CIMPL_PLAN_PROFILE%2CASSIGN_PROGRESS%2CEQUITY_RECORD_DATE%2CEX_DIVIDEND_DATE%2CPAY_CASH_DATE&quoteColumns=&filter=(SECUCODE%3D%22301060.SZ%22)&pageNumber=1&pageSize=10&sortTypes=-1&sortColumns=NOTICE_DATE&source=HSF10&client=PC&v=06611219975467866
//    private String fenHongUrl = "https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_DIVIDEND_MAIN&columns=NOTICE_DATE%2CIMPL_PLAN_PROFILE&quoteColumns=&filter=(SECUCODE%3D%22$%22)&pageNumber=1&pageSize=10";

    // 现金流方案
    // https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_GCASHFLOW&sty=APP_F10_GCASHFLOW&filter=(SECUCODE%3D%22301060.SZ%22)(REPORT_DATE%20in%20(%272022-12-31%27%2C%272021-12-31%27%2C%272020-12-31%27%2C%272019-12-31%27%2C%272018-12-31%27))&p=1&ps=5&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=07282617925747554

//    private String xianjinliu = "https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_GCASHFLOW&sty=APP_F10_GCASHFLOW&filter=(SECUCODE=\"$\")(REPORT_DATE in ('2023-12-31','2022-12-31','2021-12-31','2020-12-31','2019-12-31'))&p=1&ps=5&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=036080213294289987";

    @Resource
    private RestTemplate restTemplate;

    public List<GuPiaoSYL> export() {
        // 所有股票信息
        String result = restTemplate.getForObject(homePageUrl, String.class);

        JSONObject jsonObject = JSON.parseObject(result);
        Object list = jsonObject.getJSONObject("data").get("diff");
        List<GuPiaoSYL> collect = JSON.parseArray(JSON.toJSONString(list), GuPiaoSYL.class);

        List<GuPiaoSYL> resultList = Lists.newArrayList();

        collect.stream()
                .filter(x -> !x.getF115().contains("-"))
                .filter(x -> Double.parseDouble(x.getF115()) < 30)
                .forEach(x -> {

                    String code = null;
                    if (x.getF12().startsWith("8")) {
                        code = x.getF12() + ".BJ";
                    } else if (x.getF12().startsWith("6")) {
                        code = x.getF12() + ".SH";
                    } else {
                        code = x.getF12() + ".SZ";
                    }

                    List<GuPiaoFenHong> fenHong = getFenHong(code);
                    String nianBaoDate = getNianBaoDate(x.getF12());
                    if (StringUtils.isEmpty(nianBaoDate)) {
                        nianBaoDate = getNianBaoDate1(x.getF12());
                    }
                    List<GuPiaoXianJinLiu> xianJinLiu = getXianJinLiu(code, nianBaoDate);

                    int i=0;
                    if (fenHong.size() >= xianJinLiu.size()) {
                        for (GuPiaoFenHong guPiaoFenHong : fenHong) {
                            GuPiaoSYL syl = new GuPiaoSYL();
                            syl.setF12(x.getF12());
                            syl.setF14(x.getF14());
                            syl.setF115(x.getF115());
                            syl.setNOTICE_DATE(guPiaoFenHong.getNOTICE_DATE());
                            syl.setIMPL_PLAN_PROFILE(guPiaoFenHong.getIMPL_PLAN_PROFILE());

                            if (xianJinLiu.size() > i) {
                                syl.setREPORT_DATE(xianJinLiu.get(i).getREPORT_DATE());
                                syl.setEND_CCE(xianJinLiu.get(i).getEND_CCE());
                            }
                            resultList.add(syl);
                            i++;
                        }
                    } else {
                        for (GuPiaoXianJinLiu xianJinLiu1 : xianJinLiu) {
                            GuPiaoSYL syl = new GuPiaoSYL();
                            syl.setF12(x.getF12());
                            syl.setF14(x.getF14());
                            syl.setF115(x.getF115());
                            syl.setREPORT_DATE(xianJinLiu1.getREPORT_DATE());
                            syl.setEND_CCE(xianJinLiu1.getEND_CCE());

                            if (fenHong.size() > i) {
                                syl.setNOTICE_DATE(fenHong.get(i).getNOTICE_DATE());
                                syl.setIMPL_PLAN_PROFILE(fenHong.get(i).getIMPL_PLAN_PROFILE());
                            }
                            resultList.add(syl);
                        }
                    }

            /*String fenHongUrlFormat = getFenHongUrl1.replace("$", code);
            String fenHongResult = restTemplate.getForObject(fenHongUrlFormat, String.class);
            JSONObject fenhongJson = JSON.parseObject(fenHongResult);
            if (fenhongJson.getJSONObject("result") == null) {
                GuPiaoSYL syl = new GuPiaoSYL();
                syl.setF12(x.getF12());
                syl.setF14(x.getF14());
                syl.setF115(x.getF115());
                syl.setNOTICE_DATE("无");
                syl.setIMPL_PLAN_PROFILE("无");
                resultList.add(syl);
                return;
            }

            Object fenhongList = fenhongJson.getJSONObject("result").get("data");
            List<GuPiaoFenHong> fenList = JSON.parseArray(JSON.toJSONString(fenhongList), GuPiaoFenHong.class);
            fenList.forEach(fenhong -> {
                GuPiaoSYL syl = new GuPiaoSYL();
                syl.setF12(x.getF12());
                syl.setF14(x.getF14());
                syl.setF115(x.getF115());
                syl.setNOTICE_DATE(fenhong.getNOTICE_DATE());
                syl.setIMPL_PLAN_PROFILE(fenhong.getIMPL_PLAN_PROFILE());
                resultList.add(syl);
            });*/
                    // 处理日期
//                    String nianBaoDate = getNianBaoDate(x.getF12());
////                    System.out.println(x.getF12() + ", " + nianBaoDate);
//                    getXianJinLiu(code, nianBaoDate);

            /*String xianjinliuUrl = xianjinliu.replace("$", code);
            String xianjinliuResult = restTemplate.getForObject(xianjinliuUrl, String.class);
            System.out.println("xianjinliuResult=" + xianjinliuResult); //

            JSONObject xianjinliuJson = JSON.parseObject(xianjinliuResult);
            Object xianjinliuList = xianjinliuJson.getJSONObject("result").get("data");
            List<GuPiaoXianJinLiu> xianJinLius = JSON.parseArray(JSON.toJSONString(xianjinliuList), GuPiaoXianJinLiu.class);
            xianJinLius.forEach(xianjinliu -> System.out.println(xianjinliu.getEND_CCE()));*/

                });

        /*List<GuPiaoSYL> collect = result.getData().getDiff().stream()
                .filter(x -> !x.getF115().contains("-"))
                .filter(x -> Double.parseDouble(x.getF115()) < 30).collect(Collectors.toList());
        collect.forEach(x -> {
            System.out.println(x.getF12() + ", " + x.getF14() + ", " + x.getF115());
        });*/
        return resultList;

    }


    private final String getFenHongUrl1 = "https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_DIVIDEND_MAIN&columns=NOTICE_DATE,IMPL_PLAN_PROFILE&quoteColumns=&filter=(SECUCODE=\"$\")&pageNumber=1&pageSize=10";
    /**
     * 分红请求
     */
    private List<GuPiaoFenHong> getFenHong(String gupiaoCode) {
        String fenHongUrlFormat = getFenHongUrl1.replace("$", gupiaoCode);
        String fenHongResult = restTemplate.getForObject(fenHongUrlFormat, String.class);
        JSONObject fenhongJson = JSON.parseObject(fenHongResult);
        if (Objects.isNull(fenhongJson.getJSONObject("result"))) {
            return Lists.newArrayList();
        }
        JSONArray dateList = fenhongJson.getJSONObject("result").getJSONArray("data");
        if (Objects.isNull(dateList) || dateList.size() == 0) {
            return Lists.newArrayList();
        }
        return JSON.parseArray(JSON.toJSONString(dateList), GuPiaoFenHong.class);
    }

    private final String nianbaoDateUrl = "https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_GBALANCE&sty=SECURITY_CODE,REPORT_DATE,REPORT_TYPE,REPORT_DATE_NAME&filter=(SECURITY_CODE=\"$\")&p=1&ps=200&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=06527758916003097";
    /**
     * 获取年报日期
     * 日期url:https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_GBALANCE&sty=SECURITY_CODE,REPORT_DATE,REPORT_TYPE,REPORT_DATE_NAME&filter=(SECURITY_CODE=%22300843%22)&p=1&ps=200&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=06527758916003097
     * <p>
     * example: {"version":"bec08d5a92ab9193cb5cd2a2d11cc6d3","result":{"pages":1,"data":[{"SECURITY_CODE":"300843","REPORT_DATE":"2023-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2023三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2023-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2023中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2023-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2023一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2022年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2022三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2022中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2022一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2021年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2021三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2021中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2021一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2020年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2020三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2020中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2020一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2019-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2019年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2019-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2019中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2018-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2018年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2017-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2017年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2016-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2016年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2015-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2015年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2014-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2014年报"}],"count":22},"success":true,"message":"ok","code":0}
     *
     * @return 返回值：'2022-12-31','2021-12-31','2020-12-31','2019-12-31','2018-12-31'
     */
    private String getNianBaoDate(String gupiaoCode) {
        String nianbaoDateUrl1 = nianbaoDateUrl.replace("$", gupiaoCode);
        String nianbaoResult = restTemplate.getForObject(nianbaoDateUrl1, String.class);
        JSONObject dateJson = JSON.parseObject(nianbaoResult);
        if (Objects.isNull(dateJson.getJSONObject("result"))) {
            return null;
        }
        JSONArray dateList = dateJson.getJSONObject("result").getJSONArray("data");
        if (Objects.isNull(dateList) || dateList.size() == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (Object o : dateList) {
            JSONObject parse = JSON.parseObject(o.toString());
            if (parse.get("REPORT_TYPE").toString().contains("年报")) {
                sb.append("'").append(parse.get("REPORT_DATE").toString()).append("',");
            }
        }
        if (sb.lastIndexOf(",") > 0) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    private final String nianbaoDateUrl_ = "https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_BBALANCE&sty=SECURITY_CODE,REPORT_DATE,REPORT_TYPE,REPORT_DATE_NAME&filter=(SECURITY_CODE=\"$\")&p=1&ps=200&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=06527758916003097";
    /**
     * 获取年报日期
     * 日期url:https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_BBALANCE&sty=SECURITY_CODE,REPORT_DATE,REPORT_TYPE,REPORT_DATE_NAME&filter=(SECURITY_CODE=%22300843%22)&p=1&ps=200&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=06527758916003097
     * <p>
     * example: {"version":"bec08d5a92ab9193cb5cd2a2d11cc6d3","result":{"pages":1,"data":[{"SECURITY_CODE":"300843","REPORT_DATE":"2023-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2023三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2023-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2023中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2023-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2023一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2022年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2022三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2022中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2022-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2022一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2021年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2021三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2021中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2021-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2021一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2020年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-09-30 00:00:00","REPORT_TYPE":"三季报","REPORT_DATE_NAME":"2020三季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2020中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2020-03-31 00:00:00","REPORT_TYPE":"一季报","REPORT_DATE_NAME":"2020一季报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2019-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2019年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2019-06-30 00:00:00","REPORT_TYPE":"中报","REPORT_DATE_NAME":"2019中报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2018-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2018年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2017-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2017年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2016-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2016年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2015-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2015年报"},{"SECURITY_CODE":"300843","REPORT_DATE":"2014-12-31 00:00:00","REPORT_TYPE":"年报","REPORT_DATE_NAME":"2014年报"}],"count":22},"success":true,"message":"ok","code":0}
     *
     * @return 返回值：'2022-12-31','2021-12-31','2020-12-31','2019-12-31','2018-12-31'
     */
    private String getNianBaoDate1(String gupiaoCode) {
        String nianbaoDateUrl1 = nianbaoDateUrl_.replace("$", gupiaoCode);
        String nianbaoResult = restTemplate.getForObject(nianbaoDateUrl1, String.class);
        JSONObject dateJson = JSON.parseObject(nianbaoResult);
        if (Objects.isNull(dateJson.getJSONObject("result"))) {
            return null;
        }
        JSONArray dateList = dateJson.getJSONObject("result").getJSONArray("data");
        if (Objects.isNull(dateList) || dateList.size() == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (Object o : dateList) {
            JSONObject parse = JSON.parseObject(o.toString());
            if (parse.get("REPORT_TYPE").toString().contains("年报")) {
                sb.append("'").append(parse.get("REPORT_DATE").toString()).append("',");
            }
        }
        if (sb.lastIndexOf(",") > 0) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    private final String xianjinliu = "https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_FINANCE_GCASHFLOW&sty=APP_F10_GCASHFLOW&filter=(SECUCODE=\"$\")(REPORT_DATE in (#))&p=1&ps=5&sr=-1&st=REPORT_DATE&source=HSF10&client=PC&v=036080213294289987";
    /**
     * 现金流请求
     */
    private List<GuPiaoXianJinLiu> getXianJinLiu(String gupiaoCode, String date) {
        if (StringUtils.isEmpty(date)) {
            System.out.println("gupiaoCOde="+gupiaoCode + ", date=" +date);
            return Lists.newArrayList();
        }
        String xianjinliuUrl = xianjinliu.replace("$", gupiaoCode).replace("#", date);
        String xianjinliuResult = restTemplate.getForObject(xianjinliuUrl, String.class);
        JSONObject dateJson = JSON.parseObject(xianjinliuResult);
        if (Objects.isNull(dateJson.getJSONObject("result"))) {
            return Lists.newArrayList();
        }
        JSONArray dateList = dateJson.getJSONObject("result").getJSONArray("data");
        if (Objects.isNull(dateList) || dateList.size() == 0) {
            return Lists.newArrayList();
        }
        return JSON.parseArray(JSON.toJSONString(dateList), GuPiaoXianJinLiu.class);
    }

}
